/*
 * 代号：凤凰
 * http://www.jphenix.org
 * 2014-06-13
 * V4.0
 */
package com.jphenix.webserver.instancea;

import com.jphenix.servlet.filter.BaseFilter;
import com.jphenix.standard.docs.ClassInfo;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器监听线程
 * 
 * 2019-09-17 整理了代码格式
 * 
 * @author 刘虻
 * 2008-10-30下午05:19:24
 */
@ClassInfo({"2019-09-17 10:37","服务器监听线程"})
public class ListenAcceptThread extends Thread {

	private ServerSocket sSocket     = null; // 服务器Socket
	private Serve        serve       = null; // 服务类
	private int          returnValue = 0;    // 返回值
	private BaseFilter   baseFilter  = null; // 主过滤器
	
	/**
	 * 构造函数
	 * 2008-7-8下午04:06:50
	 */
	public ListenAcceptThread(ServerSocket sSocket,Serve serve,BaseFilter baseFilter) {
		super("Serv-ListenAcceptThread");
		this.sSocket    = sSocket;
		this.serve      = serve;
		this.baseFilter = baseFilter;
	}
	
	/**
	 * 获取返回值
	 * @author 刘虻
	 * 2008-7-8下午04:09:48
	 * @return 返回值
	 */
	public int getReturnValue() {
		return returnValue;
	}
	
	/**
	 * 覆盖方法
	 * @author 刘虻
	 * 2008-7-8下午04:06:59
	 */
	@Override
    public void run() {
		try {
			while (serve.isRunning()) {
				try {
					//获取浏览器与服务器连接Socket
					Socket socket = sSocket.accept();
					new ServeConnection(socket, serve, baseFilter);
				} catch (IOException e) {
					serve.log("Accept: " + e);
				} catch (SecurityException se) {
					serve.log("Illegal access: " + se);
				}
			}
		} catch (Throwable t) {
			serve.log("Unhandled exception: " + t + ", server is terminating.", t);
			returnValue = -1;
			return;
		} finally {
			try {
				if (sSocket != null) {
                    sSocket.close();
                }
			} catch (IOException e) {
			}
		}
	}
}
